import router, {
  asyncRoutes
} from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {
  getToken
} from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
import {
  checkArrayKey
} from '@/utils'

NProgress.configure({
  showSpinner: false
})

const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        if ((to.path === '/403' || to.path === '/404') && store.getters.roles.includes('instructor')) {
          console.log(to.path, store.getters.roles)
          next({
            path: '/Order'
          })
        } else if (to.path === '/404' && to.redirectedFrom) {
          if (from.path === '/login') {
            next({
              path: '/'
            })
          } else {
            const stmp = to.redirectedFrom
            const sArr = stmp.slice(1).split('/')
            if (checkArrayKey(sArr, asyncRoutes, 'path')) {
              next({
                path: '/403',
                replace: true
              })
            } else {
              next()
            }
          }
        } else {
          next()
        }
      } else {
        try {
          const {
            roles,
            menus
          } = await store.dispatch('user/getInfo')
          const roleArray = roles.map(e => e.name)
          const accessRoutes = await store.dispatch('permission/generateRoutes', {
            roleArray,
            menus
          })
          router.addRoutes(accessRoutes)
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
